package cn.wu.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.wu.reggie.common.ConstantUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.common.SMSUtils;
import cn.wu.reggie.entity.User;
import cn.wu.reggie.service.UserService;
import com.sun.net.httpserver.spi.HttpServerProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.Map;

import static cn.wu.reggie.common.ConstantUtil.LOGINCODE;

@RestController
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        //1 获取手机号
        String phone = user.getPhone();
        //2 生成随机的验证码
//        String code = RandomUtil.randomNumbers(4);
        //TODO 默认值
        String code = "1234";
        //3 调用工具类发送短信（只是写代码 不演示）
        System.out.println("code = " + code);
        //SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        //4 将验证码放入session
//        session.setAttribute(phone, code);
        // 优化：将验证码放入redis中 且设置有效时间5分钟 使用常量
        redisTemplate.opsForValue().set(LOGINCODE + phone, code, Duration.ofMinutes(5));

        //5 返回发送成功
        return R.success(code);
    }

    @PostMapping("login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        //1 获取用户输入的手机号验证码
        String requestCode = map.get("code");
        String phone = map.get("phone");
        //2 获取session中验证码
        //String sessionCode = (String) session.getAttribute(phone);

        // 优化 从redis中获取code
        String sessionCode = (String) redisTemplate.opsForValue().get(LOGINCODE + phone);
        //3 调用service完成验证码
        R<User> r = userService.login(phone, requestCode, sessionCode);
        //4 若用户登录成功 将用户id存入session中 把验证码从session中删除
        if (r.getCode() == 1) {
//            session.setAttribute("user",phone);
            //在session中保存用户的唯一标识 id
            session.setAttribute("user", r.getData().getId());
//            session.removeAttribute(phone);
            // 优化后 登陆成功后要从redis中移除
            redisTemplate.delete(LOGINCODE+phone);
        }
        return r;
    }

}
